package cn.czg.cms.controller;

import cn.czg.cms.common.ResultT;
import cn.czg.cms.entity.Message;
import cn.czg.cms.entity.dto.MessageDTO;
import cn.czg.cms.entity.vo.MessageConversationVO;
import cn.czg.cms.service.AuthService;
import cn.czg.cms.service.MessageService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    private final MessageService messageService;
    private final AuthService authService;

    public MessageController(MessageService messageService, AuthService authService) {
        this.messageService = messageService;
        this.authService = authService;
    }

    @PostMapping("/send")
    public ResultT<Void> sendMessage(@RequestBody MessageDTO dto) {
        Long senderId = authService.getLoginUserId(); // 你自己的登录上下文获取逻辑
        messageService.sendMessage(senderId, dto);
        return ResultT.success();
    }

    /**
     * 获取两个用户的聊天记录，支持分页
     *
     * @param userId   当前登录用户ID（必须）
     * @param peerId   对方用户ID（必须）
     * @param page     页码，默认1
     * @param pageSize 每页大小，默认20
     * @return List<Message>
     */
    @GetMapping("/history")
    public ResultT<List<Message>> getHistory(@RequestParam Long userId,
                                             @RequestParam Long peerId,
                                             @RequestParam(defaultValue = "1") int page,
                                             @RequestParam(defaultValue = "20") int pageSize) {
        // 这里建议加安全校验，确认 userId 是当前登录用户的ID
        return ResultT.success(messageService.getChatHistory(userId, peerId, page, pageSize));
    }

    @GetMapping("/conversations")
    public ResultT<List<MessageConversationVO>> getConversations(@RequestParam Long userId) {
        List<MessageConversationVO> result = messageService.getConversations(userId);
        return ResultT.success(result);
    }
}
